<?php

namespace App\Console\Commands\Setting;

use App\Models\Setting\Setting;
use Illuminate\Console\Command;

class UpdateSetting extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'setting:update {setting_key} {setting_value}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新设置表内容';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $setting      = new Setting();
        $setting_key  = $this->argument('setting_key');
        $setting_info = $setting->getSetting($setting_key);
        if (!$setting_info) {
            $this->error('Setting key '.$setting_key.' not found');
            return false;
        }

        $curr_value   = $setting_info->getValue();
        $setting_name = $setting_info->getSettingName();
        $new_value    = $this->argument('setting_value');
        $reason       = $new_value == '' ? '值为空' : ($curr_value == $new_value ? "值未改变" : "");
        if ($this->confirm("您将要更新setting `{$setting_name}` 配置: {$setting_key}的值将由 {$curr_value} 改为 {$new_value} ,请确认")) {
            $res = $setting->updateAndCache($setting_info, $new_value);
            $this->info($res ? "{$setting_key} 更新成功:{$new_value}" : "{$setting_key} 更新失败 {$reason}");
        } else {
            $this->error("您已取消此次更新");
        }
    }
}
